package org.example.order.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.example.order.VO.AdminVO;
import org.example.order.VO.LoginVO;
import org.example.order.VO.RegisterVO;
import org.example.order.entity.Admin;
import org.example.order.mapper.AdminMapper;
import org.example.order.service.AdminService;
import org.example.order.util.JWTUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Resource
    private AdminMapper AdminMapper;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public void add(Admin admin) {
        if (admin.getPassword() == null) {
            admin.setPassword("123456");
        }
        baseMapper.insert(admin);
    }

    @Override
    public void deleteById(Long id) {
        baseMapper.deleteById(id);
    }

    @Override
    public void update(Admin admin) {
        baseMapper.updateById(admin);
    }

    @Override
    public Admin selectById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public List<Admin> selectAll() {
        return baseMapper.selectList(null);
    }

    @Override
    public PageInfo<Admin> selectPage(Admin admin, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        if (admin != null && admin.getAdminName() != null) {
            wrapper.like("adminName", admin.getAdminName());
        }
        List<Admin> list = baseMapper.selectList(wrapper);
        return new PageInfo<>(list);
    }
    public  Admin selectById(int id){
        return AdminMapper.selectById(id);
    }
    public Admin getByAdminName(String Adminname){
        LambdaQueryWrapper<Admin> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getAdminName,Adminname);
        return this.getOne(wrapper);
    }
    public Admin getByPhone(String phone){
        LambdaQueryWrapper<Admin> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getPhone,phone);
        return this.getOne(wrapper);
    }
    public List<Admin> getAdminList(String keyword) {
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(keyword)) {
            wrapper.like(Admin::getAdminName, keyword)
                    .or()
                    .like(Admin::getPhone, keyword);
        }

        wrapper.orderByDesc(Admin::getCreateTime);

        // 返回 List 而不是 IPage
        return this.list(wrapper);
    }
    @Transactional(rollbackFor = Exception.class)
    public Admin register(RegisterVO registerVO){
        Admin existAdmin=this.getByAdminName(registerVO.getUsername());
        if(existAdmin!=null){
            throw new RuntimeException("用户名已存在");
        }
        if (StringUtils.hasText(registerVO.getPhone())) {
            existAdmin = this.getByPhone(registerVO.getPhone());
            if (existAdmin != null) {
                throw new RuntimeException("手机号已被注册");
            }
        }
        Admin Admin=new Admin();
        Admin.setAdminName(registerVO.getUsername());
        Admin.setPassword(passwordEncoder.encode(registerVO.getPassword()));
        Admin.setPhone(registerVO.getPhone());
        Admin.setStatus(1);
        this.save(Admin);
        return Admin;
    }
    @Transactional(rollbackFor = Exception.class)
    public AdminVO login(LoginVO loginVO, String ip) {
        Admin Admin=null;
        if(StringUtils.hasText(loginVO.getIdentifier())){
            Admin=this.getByAdminName(loginVO.getIdentifier());
        }
        if(StringUtils.hasText(loginVO.getIdentifier())&&Admin==null){
            Admin=this.getByPhone(loginVO.getIdentifier());
        }
        if(Admin==null){
            throw new RuntimeException("用户不存在");
        }
        if(!passwordEncoder.matches(loginVO.getPassword(),Admin.getPassword())){
            throw new RuntimeException("用户密码错误");
        }
        if(Admin.getStatus()==0){
            throw new RuntimeException("账号已被禁用");
        }
        Map<String, String> payload = new HashMap<>();
        payload.put("id",Admin.getId().toString());
        payload.put("level","2");
        String token= JWTUtils.getToken(payload);
        AdminMapper.updateLoginInfo(Admin.getId(), LocalDateTime.now(),ip);
        AdminVO AdminVO=new AdminVO();
        BeanUtils.copyProperties(Admin,AdminVO);
        AdminVO.setToken(token);
        return AdminVO;

    }

    public String updateAdminInfo(AdminVO adminVO) {
        // 1. 首先根据ID获取现有管理员信息
        if (adminVO.getId()==null){
            return "没有传递id";
        }
        Admin existingAdmin = this.getById(adminVO.getId());
        if (existingAdmin == null) {
            return "用户不存在"; // 如果ID不存在，返回更新失败
        }

        // 2. 创建更新对象
        Admin adminToUpdate = new Admin();
        adminToUpdate.setId(adminVO.getId()); // 设置ID用于条件更新

        // 3. 选择性地设置要更新的字段（只更新非null和非空字符串的字段）
        if (adminVO.getUsername() != null && !adminVO.getUsername().isEmpty()) {
            adminToUpdate.setAdminName(adminVO.getUsername());
        }

        if (adminVO.getPhone() != null && !adminVO.getPhone().isEmpty()) {
            adminToUpdate.setPhone(adminVO.getPhone());
        }

        // 状态是基本类型，不需要null检查，但应该确认它在VO中是否被设置
        // 可以根据业务需求决定是否更新状态
        adminToUpdate.setStatus(adminVO.getStatus());

        // 对于日期和其他复杂类型，也需要非null检查
        if (adminVO.getLastLoginTime() != null) {
            // 可能需要日期格式转换
            adminToUpdate.setLastLoginTime(adminVO.getLastLoginTime());
        }

        if (adminVO.getLastLoginIp() != null && !adminVO.getLastLoginIp().isEmpty()) {
            adminToUpdate.setLastLoginIp(adminVO.getLastLoginIp());
        }

//        if (adminVO.getToken() != null && !adminVO.getToken().isEmpty()) {
//            adminToUpdate.setToken(adminVO.getToken());
//        }

        // 4. 执行更新，只更新非null字段
        if(this.updateById(adminToUpdate)){
            return "修改成功";
        }
        return "修改失败";
    }

    public boolean updatePassword(Long AdminId, String oldPassword, String newPassword) {
        Admin Admin=this.getById(AdminId);
        if(Admin ==null){
            throw new RuntimeException("用户不存在");
        }
        if(!passwordEncoder.matches(oldPassword,Admin.getPassword())){
            throw new RuntimeException("原密码错误");
        }
        Admin.setPassword(passwordEncoder.encode(newPassword));
        return this.updateById(Admin);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean removeAdmin(Long AdminId) {
        // MyBatis Plus 的 removeById 会自动处理逻辑删除
        return this.removeById(AdminId);
    }


    @Transactional(rollbackFor = Exception.class)
    public boolean removeAdminBatch(List<Long> AdminIds) {
        // MyBatis Plus 的 removeByIds 会自动处理逻辑删除
        return this.removeByIds(AdminIds);
    }


    @Transactional(rollbackFor = Exception.class)
    public boolean restoreAdmin(Long AdminId) {
        // 手动将 isDeleted 字段设置为 0，恢复用户
        return adminMapper.restoreAdmin(AdminId)>0;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean restoreAdminBatch(List<Long> AdminIds) {
        // 批量恢复用户
        return adminMapper.restoreUserBatch(AdminIds)>0;
    }

}
